/**
 * 用户管理模块 - 维护每个频道的用户状态和权限
 */

// 用户角色枚举
const USER_ROLES = {
  STORYTELLER: 'storyteller',  // 说书人
  PLAYER: 'player',           // 玩家
  SPECTATOR: 'spectator'      // 观众/访客
};

// 用户状态枚举
const USER_STATUS = {
  ONLINE: 'online',           // 在线
  OFFLINE: 'offline',         // 离线
  AWAY: 'away'               // 暂离
};

// 语音聊天状态枚举
const VOICE_STATUS = {
  PUBLIC: 'public',           // 在公聊
  PRIVATE: 'private',         // 在私聊
  NONE: 'none'               // 未参与语音
};

/**
 * 用户数据结构
 */
class User {
  constructor(playerId, role = USER_ROLES.SPECTATOR) {
    this.playerId = playerId;
    this.role = role;
    this.status = USER_STATUS.ONLINE;
    this.voiceStatus = VOICE_STATUS.NONE;
    
    // 基本信息
    this.displayName = this._generateDisplayName(role);
    this.joinedAt = new Date();
    this.lastActiveAt = new Date();
    
    // 游戏相关
    this.seatIndex = -1;        // 座位号，-1表示未入座
    this.isSeated = false;      // 是否已入座
    
    // 语音相关
    this.isMuted = false;       // 是否被静音
    this.canVoiceChat = true;   // 是否允许语音聊天
    this.currentVoiceRoom = null; // 当前语音房间ID
    
    // 权限相关
    this.permissions = this._generatePermissions(role);
    
    // 连接信息
    this.connectionId = null;   // WebSocket连接ID
    this.latency = 0;          // 网络延迟
    this.connectionQuality = 'good'; // 连接质量
  }

  /**
   * 生成显示名称
   */
  _generateDisplayName(role) {
    switch (role) {
      case USER_ROLES.STORYTELLER:
        return '【⭐】说书人';
      case USER_ROLES.PLAYER:
        return '玩家';
      case USER_ROLES.SPECTATOR:
        return '【访客】';
      default:
        return '未知用户';
    }
  }

  /**
   * 生成角色权限
   */
  _generatePermissions(role) {
    const basePermissions = {
      canViewGame: true,
      canChat: true,
      canVoiceChat: false,
      canPrivateChat: false,
      canManagePlayers: false,
      canManageGame: false,
      canManageVoice: false
    };

    switch (role) {
      case USER_ROLES.STORYTELLER:
        return {
          ...basePermissions,
          canVoiceChat: true,
          canPrivateChat: true,
          canManagePlayers: true,
          canManageGame: true,
          canManageVoice: true
        };
      
      case USER_ROLES.PLAYER:
        return {
          ...basePermissions,
          canVoiceChat: true,
          canPrivateChat: true
        };
      
      case USER_ROLES.SPECTATOR:
        return {
          ...basePermissions,
          canVoiceChat: false,
          canPrivateChat: false
        };
      
      default:
        return basePermissions;
    }
  }

  /**
   * 更新用户角色
   */
  updateRole(newRole) {
    if (Object.values(USER_ROLES).includes(newRole)) {
      this.role = newRole;
      this.displayName = this._generateDisplayName(newRole);
      this.permissions = this._generatePermissions(newRole);
      this.lastActiveAt = new Date();
      return true;
    }
    return false;
  }

  /**
   * 入座
   */
  takeSeat(seatIndex, playerName) {
    this.seatIndex = seatIndex;
    this.isSeated = true;
    if (playerName) {
      this.displayName = playerName;
    }
    // 入座后自动升级为玩家
    if (this.role === USER_ROLES.SPECTATOR) {
      this.updateRole(USER_ROLES.PLAYER);
    }
    this.lastActiveAt = new Date();
  }

  /**
   * 离座
   */
  leaveSeat() {
    this.seatIndex = -1;
    this.isSeated = false;
    // 离座后降级为观众（除非是说书人）
    if (this.role === USER_ROLES.PLAYER) {
      this.updateRole(USER_ROLES.SPECTATOR);
      this.displayName = '【访客】';
    }
    this.lastActiveAt = new Date();
  }

  /**
   * 更新语音状态
   */
  updateVoiceStatus(status, roomId = null) {
    this.voiceStatus = status;
    this.currentVoiceRoom = roomId;
    this.lastActiveAt = new Date();
  }

  /**
   * 更新活跃时间
   */
  updateActivity() {
    this.lastActiveAt = new Date();
  }

  /**
   * 获取用户摘要信息（用于广播）
   */
  getSummary() {
    return {
      playerId: this.playerId,
      role: this.role,
      displayName: this.displayName,
      status: this.status,
      voiceStatus: this.voiceStatus,
      isSeated: this.isSeated,
      seatIndex: this.seatIndex,
      isMuted: this.isMuted,
      permissions: this.permissions,
      joinedAt: this.joinedAt,
      lastActiveAt: this.lastActiveAt
    };
  }

  /**
   * 获取详细信息（用于管理）
   */
  getDetailedInfo() {
    return {
      ...this.getSummary(),
      canVoiceChat: this.canVoiceChat,
      currentVoiceRoom: this.currentVoiceRoom,
      connectionId: this.connectionId,
      latency: this.latency,
      connectionQuality: this.connectionQuality
    };
  }
}

/**
 * 频道用户管理器
 */
class ChannelUserManager {
  constructor(channelId) {
    this.channelId = channelId;
    this.users = new Map(); // playerId -> User
    this.storytellerId = null; // 当前说书人ID
    this.createdAt = new Date();
  }

  /**
   * 添加用户
   */
  addUser(playerId, role = USER_ROLES.SPECTATOR, connectionId = null) {
    if (this.users.has(playerId)) {
      // 更新现有用户的连接信息
      const user = this.users.get(playerId);
      user.connectionId = connectionId;
      user.status = USER_STATUS.ONLINE;
      user.updateActivity();
      return user;
    }

    const user = new User(playerId, role);
    user.connectionId = connectionId;
    
    // 如果是说书人，设置说书人ID
    if (role === USER_ROLES.STORYTELLER) {
      this.storytellerId = playerId;
    }
    
    this.users.set(playerId, user);
    return user;
  }

  /**
   * 移除用户
   */
  removeUser(playerId) {
    const user = this.users.get(playerId);
    if (user) {
      user.status = USER_STATUS.OFFLINE;
      // 如果是说书人离开，清空说书人ID
      if (playerId === this.storytellerId) {
        this.storytellerId = null;
      }
      this.users.delete(playerId);
      return user;
    }
    return null;
  }

  /**
   * 获取用户
   */
  getUser(playerId) {
    return this.users.get(playerId);
  }

  /**
   * 获取说书人
   */
  getStoryteller() {
    return this.storytellerId ? this.users.get(this.storytellerId) : null;
  }

  /**
   * 获取所有在线用户
   */
  getOnlineUsers() {
    return Array.from(this.users.values()).filter(user => user.status === USER_STATUS.ONLINE);
  }

  /**
   * 获取已入座玩家
   */
  getSeatedPlayers() {
    return Array.from(this.users.values()).filter(user => user.isSeated);
  }

  /**
   * 获取观众
   */
  getSpectators() {
    return Array.from(this.users.values()).filter(user => user.role === USER_ROLES.SPECTATOR);
  }

  /**
   * 检查用户权限
   */
  checkPermission(playerId, permission) {
    const user = this.users.get(playerId);
    return user ? user.permissions[permission] : false;
  }

  /**
   * 用户入座
   */
  userTakeSeat(playerId, seatIndex, playerName) {
    const user = this.users.get(playerId);
    if (user) {
      user.takeSeat(seatIndex, playerName);
      return true;
    }
    return false;
  }

  /**
   * 用户离座
   */
  userLeaveSeat(playerId) {
    const user = this.users.get(playerId);
    if (user) {
      user.leaveSeat();
      return true;
    }
    return false;
  }

  /**
   * 更新用户语音状态
   */
  updateUserVoiceStatus(playerId, status, roomId = null) {
    const user = this.users.get(playerId);
    if (user) {
      user.updateVoiceStatus(status, roomId);
      return true;
    }
    return false;
  }

  /**
   * 获取用户列表摘要（用于广播）
   */
  getUsersSummary() {
    const users = {};
    this.users.forEach((user, playerId) => {
      users[playerId] = user.getSummary();
    });
    return {
      channelId: this.channelId,
      storytellerId: this.storytellerId,
      users,
      createdAt: this.createdAt,
      onlineCount: this.getOnlineUsers().length,
      seatedCount: this.getSeatedPlayers().length
    };
  }
}

/**
 * 全局用户管理器
 */
class GlobalUserManager {
  constructor() {
    this.channels = new Map(); // channelId -> ChannelUserManager
  }

  /**
   * 获取或创建频道用户管理器
   */
  getChannelManager(channelId) {
    if (!this.channels.has(channelId)) {
      this.channels.set(channelId, new ChannelUserManager(channelId));
    }
    return this.channels.get(channelId);
  }

  /**
   * 移除频道
   */
  removeChannel(channelId) {
    this.channels.delete(channelId);
  }

  /**
   * 获取统计信息
   */
  getStats() {
    let totalUsers = 0;
    let totalChannels = this.channels.size;
    
    this.channels.forEach(channel => {
      totalUsers += channel.getOnlineUsers().length;
    });

    return {
      totalChannels,
      totalUsers,
      channels: Array.from(this.channels.keys())
    };
  }
}

module.exports = {
  USER_ROLES,
  USER_STATUS,
  VOICE_STATUS,
  User,
  ChannelUserManager,
  GlobalUserManager
};